package com.nondo.dean.auth.service.impl;

import com.nondo.dean.auth.common.crypto.password.PasswordEncoder;
import com.nondo.dean.auth.domain.Role;
import com.nondo.dean.auth.domain.User;
import com.nondo.dean.auth.domain.UserExample;
import com.nondo.dean.auth.mapper.UserMapper;
import com.nondo.dean.auth.module.UserBean;
import com.nondo.dean.auth.service.RoleService;
import com.nondo.dean.auth.service.UserRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author xiaofan
 * @Description: sap返回用户入库
 * @throws
 * @date 2018-05-1115:47
 * @Version 0.1
 */
@Component
public class SapUserServiceImpl {

    private static final Logger log = LoggerFactory.getLogger(SapUserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @Value("${init.data.role}")
    private String roleCode;

    /**
     * 检查经销商是否存在重复数据
     *
     * @return
     */
    public List<User> checkDuplicateUser(User user) {
        //检查是否存在重复的数据
        UserExample exampleCheck = new UserExample();
        exampleCheck.createCriteria().andUsernameEqualTo(user.getUsername());
        return this.userMapper.selectByExample(exampleCheck);

    }

    /**
     * 经销商入库
     *
     * @param userBean
     * @return
     */
    public int insertUser(List<UserBean> userBean) {

        Role role = roleService.findByCode(roleCode);

        int count = 0;
        for (UserBean bean : userBean) {
            User users = new User();
            if ("X".equals(bean.getDelFlag())) {
                users.setDelFlag(User.DEL_FLAG_DELETE);
            } else {
                users.setDelFlag(User.DEL_FLAG_NORMAL);
            }
            users.setUsername(bean.getUserName());
            users.setPhone(bean.getTelphone());
            users.setMobile(bean.getMobile());
            List<User> userList = checkDuplicateUser(users);
            if (!userList.isEmpty()) {
                for (User item : userList) {
                    users.setId(item.getId());
                    count += userMapper.updateByPrimaryKeySelective(users);

                    if (role != null) {
                        userRoleService.saveUserRole(item.getId(), role.getId());
                    }
                }
            } else {
                users.setPassword(passwordEncoder.encode("123456"));
                count += userMapper.insertSelective(users);
                if (role != null) {
                    userRoleService.saveUserRole(users.getId(), role.getId());
                }
            }
        }

        return count;
    }


}
